var protocol = location.protocol === 'https:' ? 'wss://' : 'ws://';
WS = new ReconnectingWebSocket(protocol + WS);

WS.onopen = function () {
    console.log('握手成功');
    var login_info = '{"type":"youke_login","fromid":' + youke_info.from_id + ',"toid":' + kefu_info.to_id + ',"name":"' + youke_info.from_nick + '","avatar":"' + youke_info.from_avatar + '"}';
    WS.send(login_info);
    eventPageState(pageStateCallback);
    //每30秒ping服务器
    setInterval(function () {
        WS.send('{"type":"ping"}');
    }, 30000);
    setTimeout(function () {
        var message = '{"from_id":"' + youke_info.from_id + '","from_nick":"' + youke_info.from_nick + '","from_avatar":"' + youke_info.from_avatar + '","to_id":"' + kefu_info.to_id + '","to_nick":"' + kefu_info.to_nick + '","to_avatar":"' + kefu_info.to_avatar + '"}';
        hook('autosend', message, 1);
    }, 3000);
};

var titleTimerID;    //定义时间变量
function pageStateCallback(state){
    // 激活当前页面
    if( state != 'hidden'){
        clearTimeout(titleTimerID);
        var title = $("title") ;
        if( title.attr('text') ){
            title.html(title.attr('text'));
            title.attr('text','');
        }
    }
}

function scrollTitle(){
    clearTimeout(titleTimerID);
    document.title = document.title.substring(1, document.title.length) + document.title.substring(0, 1);
    text = document.title.substring(0, document.title.length);
    timerID = setTimeout("scrollTitle()", 100)
}

function changeTitle(){
    if( _statePage == 'hidden' ){
        $("title").attr('text',$("title").html());
        $("title").html('有新消息提示!您有新消息请注意查收');
        scrollTitle();
    }
}

WS.onmessage = function (evt) {
    let data = JSON.parse(evt.data);
    // console.log('onmessage');
    // console.log(data);
    switch (data.type) {
        case 'ping':
            WS.send(JSON.stringify({
                type: 'ping',
                fromid: youke_info.from_id
            }));
            break;
        // 已经被分配了客服
        case 'connect':
            // showMessage('客服 ' + data.data.kf_name + ' 为您服务');
            break;
        case 'helloMessage':
            showMessage(data.data.content);
            break;
        case 'no_online':
            showMessage('对方不在线，已留言');
            offlinerecord();//离线弹窗
            var message = '{"uid":"' + youke_info.from_id + '"}';
            unread('add',message);
            message = '{"from_id":"' + youke_info.from_id + '","from_nick":"' + youke_info.from_nick + '","from_avatar":"' + youke_info.from_avatar + '","to_id":"' + kefu_info.to_id + '","to_nick":"' + kefu_info.to_nick + '","to_avatar":"' + kefu_info.to_avatar + '"}';
            hook('no_online',message,0)
            break;
        // case 'kf_online':
        //     showMessage(data.data.kf_name + '客服上线了');
        //     break;
        case 'zj_yk_online':
            relinkMessage(data.data);
            break;
        case 'say':
            changeTitle();
            if (data.data.utype == 'say_to') {
                playPrompt('#new-mess');
                we_im_update_current_left_message(data.data);
            }
            break;
        case 'goods':
            layer.open({
                type: 2,
                title: '商品信息',
                skin: 'layui-layer-rim-record',
                area: ['410px', '550px'],
                content: data.data,
                cancel: function (index, layero) {
                    $(layero).find('a.layui-layer-close').prop('target', '_self');
                }
            });
            break;
    }
};

WS.onclose = function (e) {

};

WS.onerror = function (e) {

};

$(function () {
    initShortcut();
    loadMessageHistory('bottom');
    /**
     * 发送文本信息
     */
    $('#send').click(function () {
        var falg = '';
        var txt = htmlEncode($.trim($('#text').val()));
        var text = txt.replace(/\[.+?\]/g, function (a, b) {
            falg = ' img';
            return "<img src='" + faces_lists[a] + "'/>";
        });
        if (!text) return;
        emptyShowMessage();
        // utype=say_from代表游客给客服聊天
        text = "" + text + "";/*消息记录数据库*/
        var message = '{"data":"' + text + '","type":"say-text","utype":"say_from","from_id":"' + youke_info.from_id + '","from_nick":"' + youke_info.from_nick + '","from_avatar":"' + youke_info.from_avatar + '","to_id":"' + kefu_info.to_id + '","to_nick":"' + kefu_info.to_nick + '","to_avatar":"' + kefu_info.to_avatar + '"}';
        message = message.replace(/\n/g, "<br/>");
        text = text.replace(/\n/g, "<br/>");

        var from_tpl = '<div class="msg guest">' +
            '<div class="msg-right">' +
            '<div class="msg-host">' +
            '<img src="' + youke_info.from_avatar + '">' +
            '</div>' +
            '<div class="msg-ball' + falg + '">' + text + '</div>' +
            '</div>' +
            '</div>';
        $('#text').val("");
        playPrompt();
        $('#msgs').append(from_tpl);
        scrollTopfooter();
        updateConsultingNumber(
            youke_info.from_id,
            kefu_info.to_id
        );
        WS.send(message);
        hook('user_send', message, false);
        hook('goods_check', message, false);
    });

    /**
     * 上传图片
     */
    $("#upload_img input").change(function () {
        var formData = new FormData();
        formData.append('ajaxupimg', $('input[name="upload_img"]').get(0).files[0]);
        formData.append('user_id', youke_info.from_id);
        formData.append('field', 'ajaxupimg');
        formData.append('user_type', 2);
        $('input[name="upload_img"]').val('');
        $.ajax({
            url: IM_config.ajaxupimg,
            method: 'post',
            data: formData,
            dataType: 'json',
            processData: false,
            contentType: false,
            cache: false,
            async: false,
            success: function (res) {
                if (res.errno == 0) {
                    emptyShowMessage();
                    var text = "<div class='mess-img'><img src='" + res.data[0] + "' /></div>";
                    // utype=say_to代表客服给游客聊天
                    var message = '{"data":"' + text + '","type":"say-img","utype":"say_from","from_id":"' + youke_info.from_id + '","from_nick":"' + youke_info.from_nick + '","from_avatar":"' + youke_info.from_avatar + '","to_id":"' + kefu_info.to_id + '","to_nick":"' + kefu_info.to_nick + '","to_avatar":"' + kefu_info.to_avatar + '"}';
                    var from_tpl = '<div class="msg guest">' +
                        '<div class="msg-right">' +
                        '<div class="msg-host">' +
                        '<img src="' + youke_info.from_avatar + '">' +
                        '</div>' +
                        '<div class="msg-ball img">' + text + '</div>' +
                        '</div>' +
                        '</div>';
                    playPrompt();
                    $('#msgs').append(from_tpl);
                    scrollTopfooter();
                    updateConsultingNumber(
                        youke_info.from_id,
                        kefu_info.to_id
                    );
                    WS.send(message);
                }
            }
        });
    });

    /**
     * 上传文件
     */
    $("#upload_file input").change(function () {
        var formData = new FormData();
        formData.append('ajaxupfile', $('input[name="upload_file"]').get(0).files[0]);
        formData.append('user_id', youke_info.from_id);
        formData.append('field', 'ajaxupfile');
        formData.append('user_type', 2);
        $('input[name="upload_file"]').val('');
        $.ajax({
            url: IM_config.ajaxupfile,
            method: 'post',
            data: formData,
            dataType: 'json',
            processData: false,
            contentType: false,
            cache: false,
            async: false,
            success: function (res) {
                if (res.errno == 0) {
                    emptyShowMessage();
                    var text = "<div class='mess-file'><a href='" + res.data[0] + "' target='_blank'>查看文件</a></div>";
                    // utype=say_to代表客服给游客聊天
                    var message = '{"data":"' + text + '","type":"say-file","utype":"say_from","from_id":"' + youke_info.from_id + '","from_nick":"' + youke_info.from_nick + '","from_avatar":"' + youke_info.from_avatar + '","to_id":"' + kefu_info.to_id + '","to_nick":"' + kefu_info.to_nick + '","to_avatar":"' + kefu_info.to_avatar + '"}';
                    var from_tpl = '<div class="msg guest">' +
                        '<div class="msg-right">' +
                        '<div class="msg-host">' +
                        '<img src="' + youke_info.from_avatar + '">' +
                        '</div>' +
                        '<div class="msg-ball">' + text + '</div>' +
                        '</div>' +
                        '</div>';
                    playPrompt();
                    $('#msgs').append(from_tpl);
                    scrollTopfooter();
                    updateConsultingNumber(
                        youke_info.from_id,
                        kefu_info.to_id
                    );
                    WS.send(message);
                }
            }
        });
    });

    /**
     * 显示小头像
     */
    $('#pnlWarn .pnl-warn-free').click(function () {
        let faces = "";
        let face_main = $('#emojiPnl');
        if (face_main.find('img').length <= 0) {
            $.each(faces_lists, function (title, img) {
                faces += '<img title="' + title + '" src="' + img + '"/>';
            });
            face_main.html(faces);
        }
        $('#pnlExt,#emojiPnl').toggleClass('hide');
    });

    /**
     * 点击编辑器
     */
    $('#text').click(function () {
        $('#pnlExt,#emojiPnl').addClass('hide');
    });

    /**
     * 点击小头像
     */
    $('body').on('click', '#emojiPnl img', function () {
        $('#pnlExt,#emojiPnl').addClass('hide');
        insertAtCaret($("#text"), $(this).attr('title'));
    });

    /**
     * 上滚轮获取历史记录
     */
    $('#msgs').on("mousewheel DOMMouseScroll", function (e) {
        var delta = (e.originalEvent.wheelDelta && (e.originalEvent.wheelDelta > 0 ? 1 : -1)) ||  // chrome & ie
            (e.originalEvent.detail && (e.originalEvent.detail > 0 ? -1 : 1));// firefox
        $('#histStart').text('加载中...');
        if (delta > 0 && $('#show').scrollTop() == 0) {
            loadMessageHistory('top');
        }
    });

    /**
     * tab
     */
    $('.pnl-tabs .tab-btn').click(function () {
        $(this).addClass('active').siblings().removeClass('active')
        $('.tabs-lists .pnl-hot').eq($(this).index()).show().siblings().hide()
    });

    /**
     * 评价客服
     */
    $('#evalBtn').click(function () {
        $.post('/chat/say/evaluation.html', {cuid: kefu_info.to_id}, function (r) {
            if (r.code == 200) {
                layer.open({
                    title: ['您对我还满意吗？']
                    , skin: 'layui-layer-rim-top'
                    , content: '<div class="satisfactionBox">' + r.data + '</div>'
                    , btn: ['提交', '取消']
                    , yes: function (index) {
                        var data = [];
                        $.each($('.satisfactionBox .evaluate-score'), function (index, item) {
                            data.push({
                                score: $(this).attr('data-score'),
                                sname: $(this).find('input').attr('name')
                            });
                        });
                        $.post('/chat/say/addevaluation.html', {
                            ykid: youke_info.from_id,
                            kfid: kefu_info.to_id,
                            data: data,
                            stext: $('.about-text').val()
                        }, function (r2) {
                            we_im_msg(r2.data);
                            if (r2.code == 200) {
                                setTimeout(function () {
                                    layer.close(index);
                                    $('#evalBtn').hide();
                                }, 2000);
                            }
                        });
                    }
                });
            }
        });
    });

    /**
     * 点击评分
     */
    $('body').on('click', '.star', function (row) {
        let light = '/images/star/star-1.png';
        let dark = '/images/star/star-3.png';
        let star = '/images/star/star-2.png';
        let index = row.target.dataset.id;
        $(this).parent().find('.star').attr('src', star);
        switch (index) {
            case '1':
                $(this).attr('src', dark);
                $(this).parent('.evaluate-item').attr('data-score', 1)
                break;
            case '2':
                $(this).attr('src', dark);
                $(this).prev('.star').attr('src', dark)
                $(this).parent('.evaluate-item').attr('data-score', 2)
                break;
            case '3':
                $(this).attr('src', light);
                $(this).prevAll('.star').attr('src', light);
                $(this).parent('.evaluate-item').attr('data-score', 3)
                break;
            case '4':
                $(this).attr('src', light);
                $(this).prevAll('.star').attr('src', light)
                $(this).parent('.evaluate-item').attr('data-score', 4)
                break;
            case '5':
                $(this).parent().find('.star').attr('src', light);
                $(this).parent('.evaluate-item').attr('data-score', 5)
                break;
        }
    });

    /**
     * 点击常见问题
     */
    $('#hots .rel-item').click(function () {
        var obj = $(this);
        $.post(IM_config.getComaskContent, {id: obj.attr('data-id')}, function (r) {
            if (r.code == 200) {
                var from_tpl = '<div class="msg guest">' +
                    '<div class="msg-right">' +
                    '<div class="msg-host">' +
                    '<img src="' + youke_info.from_avatar + '">' +
                    '</div>' +
                    '<div class="msg-ball">' +
                    '<div class="mess-txt">' + obj.text() + '</div>' +
                    '</div>' +
                    '</div>' +
                    '</div>' +
                    '<div class="msg guest">' +
                    '<div class="msg-left">' +
                    '<div class="msg-host"><img src="' + kefu_info.to_avatar + '"></div>' +
                    '<div class="msg-ball">' + r.data + '</div>' +
                    '</div>' +
                    '</div>';
                emptyShowMessage();
                scrollTopfooter();
                $('#msgs').append(from_tpl);
            }
        });
    });

    /**
     * 显示发送快捷键
     */
    $('#showinfo').click(function () {
        $('#fuceng').toggle();
        if (Cookies.get('chat-shortcuts') == 1) {
            $('#type1').addClass('selected-li');
            $('#type2').removeClass('selected-li');
        } else {
            $('#type2').addClass('selected-li');
            $(' #type1').removeClass('selected-li');
        }
    });

    $(document).keypress(function (e) {
        var shortcuts = Cookies.get('chat-shortcuts');
        if ((e.which == 13 && e.ctrlKey) || (e.which == 10 && e.ctrlKey)) {
            var content = $("#text").val();
            $("#text").val(content + "\n");
            if (shortcuts == 2) {
                $('#send').click();
            }
        } else if (e.which == 13) {
            if (shortcuts == 1) {
                $('#send').click();
            }
        }
    });

    /**
     * 点击发送快捷键
     */
    $('#fuceng ul li').click(function () {
        Cookies.set('chat-shortcuts', $(this).attr('type'));
        $(this).addClass('selected-li').siblings().removeClass('selected-li');
    });

    /**
     * 聊天记录中的语音播放
     */
    $('body').on('click', '.guest .mess-audio', function () {
        playAudio($(this));
    });
});

// 播放暂停切换
function playAudio(mess) {
    var media = mess.find('audio')[0];
    media_play(media);
    mess.find('i').addClass('weight');
    media.onended = function () {
        mess.find('i').removeClass('weight');
    };
    // var media = mess.find('audio')[0];
    // if(media.paused) {
    //     media_play(media);
    //     mess.find('i').addClass('weight');
    // } else {
    //     media_pause(media);
    //     mess.find('i').removeClass('weight');
    // }
    // media.onended = function () {
    //     mess.find('i').removeClass('weight');
    // };
}

// 播放
function media_play(media) {
    media.play();
}

// 暂停
function media_pause(media) {
    media.pause();
}

/**
 * 显示录音
 */
var index = [9, 8, 7, 6, 5, 4, 3, 2, 1, 2, 3, 4, 5, 6, 7, 8, 9];
var num = index.length;
var timer = null; //用于清除计时器
var audio = null;
var recorder = null;
var mp3Blob = null;
var audio_layer = null;

function getaudio() {
    audio_layer = layer.open({
        type: 1,
        title: '',
        skin: 'layui-layer-audio',
        closeBtn: 0,
        anim: 2,
        shadeClose: true,
        content: '<button class="btn btn-round btn-default" onclick="funStart(this);" id="btnStart" disabled>录制</button><button class="btn btn-round btn-default" onclick="funStop(this);" id="btnStop" disabled>发送</button>',
        end: function () {
            clearInterval(timer);
        }
    });
    audio = $('.layui-layer-audio');
    setTimer();
    recorder = new MP3Recorder({
        debug: true,
        funOk: function () {
            btnStart.disabled = false;
        },
        funCancel: function (msg) {
            recorder = null;
        }
    });
}

// 录音轮播
function setTimer() {
    timer = setInterval(function () {
        setTimeout(function () {
            num++;
            audio.css("background", "url('/static/common/images/ic_record@2x.png') no-repeat 28px 16px/64px 104px, url('/static/common/images/ic_record_ripple@2x-" + index[num] + ".png') no-repeat 111.2px 32px/28.8px 88px rgba(0, 0, 0, .7)");
        }, 70);
        if (num >= index.length - 1) {
            num = 0;
        }
    }, 70);
}

function funStart(button) {
    btnStart.disabled = true;
    btnStop.disabled = false;
    recorder.start();
}

function funStop(button) {
    recorder.stop();
    btnStart.disabled = false;
    btnStop.disabled = true;
    recorder.getMp3Blob(function (blob) {
        mp3Blob = blob;
        funUpload();
    });
}

/**
 * 上传音频
 */
function funUpload() {
    var formData = new FormData();
    mp3Blob = new File([mp3Blob], encodeURIComponent('audio_recording_' + new Date().getTime() + '.mp3'));
    formData.append('file', mp3Blob);
    $.ajax({
        url: IM_config.ajaxupaudio,
        method: 'post',
        data: formData,
        dataType: 'json',
        processData: false,
        contentType: false,
        cache: false,
        async: false,
        success: function (res) {
            if (res.errno == 0) {
                emptyShowMessage();
                var text = "<div class='mess-audio'><audio src='" + res.data[0] + "'></audio><i class='iconfont icon-yuyin'></i></div>";
                // utype=say_to代表客服给游客聊天
                var message = '{"data":"' + text + '","type":"say-audio","utype":"say_from","from_id":"' + youke_info.from_id + '","from_nick":"' + youke_info.from_nick + '","from_avatar":"' + youke_info.from_avatar + '","to_id":"' + kefu_info.to_id + '","to_nick":"' + kefu_info.to_nick + '","to_avatar":"' + kefu_info.to_avatar + '"}';
                var from_tpl = '<div class="msg guest">' +
                    '<div class="msg-right">' +
                    '<div class="msg-host">' +
                    '<img src="' + youke_info.from_avatar + '">' +
                    '</div>' +
                    '<div class="msg-ball">' + text + '</div>' +
                    '</div>' +
                    '</div>';
                playPrompt();
                $('#msgs').append(from_tpl);
                scrollTopfooter();
                updateConsultingNumber(
                    youke_info.from_id,
                    kefu_info.to_id
                );
                WS.send(message);
                layer.close(audio_layer);
            }
        }
    });
}

/**
 * 提示弹窗
 * @param msg
 * @returns {boolean}
 */
function we_im_msg(msg) {
    layer.msg(msg);
    return false;
}

/**
 * 转接
 */
function relinkMessage(data) {
    $.post(IM_config.saychaturl, {code: window.location.href, cuid: data.kf_id}, function (r) {
        if (r.code == 200) {
            $('#msgs').html("");
            window.history.pushState(null, null, r.url);
            kefu_info.to_id = data.kf_id;
            kefu_info.to_nick = data.kf_nick;
            kefu_info.to_avatar = data.kf_avatar;
        }
    });
}

/**
 * 更新咨询次数
 */
function updateConsultingNumber(ykid, kfid) {
    $.post(IM_config.updateConsultingNumber, {ykid: ykid, kfid: kfid}, function () {
    });
}

/**
 * 到底部
 */
function scrollTopfooter() {
    setTimeout(function () {
        $('#show').scrollTop($("#show")[0].scrollHeight);
    }, 10);
}

/**
 * 清空客服提示信息
 */
function emptyShowMessage() {
    $('#unreadLine').addClass('hide').find('ul').html("");
}

/**
 * 提示消息
 */
function showMessage(content) {
    var unreadLine = $('#unreadLine');
    unreadLine.removeClass('hide');
    unreadLine.find('ul').after('<li><span class="unread">' + content + '</span></li>');
}

/**
 * 更新客服聊天信息
 */
function we_im_update_current_left_message(data) {
    var from_tpl = '<div class="msg guest">' +
        '<div class="msg-left">' +
        '<div class="msg-host">' +
        '<img src="' + data.send_avatar + '">' +
        '</div>' +
        '<div class="msg-ball">' + data.content + '</div>' +
        '</div>' +
        '</div>';
    $('#msgs').append(from_tpl);
    $("#show").animate({
        scrollTop: $("#show").prop("scrollHeight")
    }, 50);
}

/**
 * 更新游客聊天信息
 */
function we_im_update_current_right_message(data) {
    var from_tpl = '<div class="msg guest">' +
        '<div class="msg-right">' +
        '<div class="msg-host">' +
        '<img src="' + data.receive_avatar + '">' +
        '</div>' +
        '<div class="msg-ball">' + data.content + '</div>' +
        '</div>' +
        '</div>';
    $('#msgs').append(from_tpl);
    $('#show').scrollTop($("#show")[0].scrollHeight);
}

/**
 * 加载历史记录
 */
function loadMessageHistory(direction) {
    var hist = $('#histStart');
    var load_page = parseInt(hist.attr('page'));
    if (hist.attr('sw') == 'off') {
        hist.text('没有消息了');
        return;
    }

    $.ajax({
        type: "post",
        url: IM_config.loadMessHistory,
        data: {
            fromid: youke_info.from_id,
            toid: kefu_info.to_id,
            page: load_page
        },
        dataType: "json",
        success: function (r) {
            if (r.code == 200) {
                var message = "";
                $.each(r.data, function (index, item) {
                    if (item.utype == 'say_to') {
                        message += '<div class="msg guest">' +
                            '<div class="msg-left">' +
                            '<div class="msg-host"><img src="' + item.send_avatar + '"></div>' +
                            '<div class="msg-ball">' + item.content + '</div>' +
                            '</div>' +
                            '</div>';
                    } else {
                        message += '<div class="msg guest">' +
                            '<div class="msg-right">' +
                            '<div class="msg-host"><img src="' + item.send_avatar + '"></div>' +
                            '<div class="msg-ball">' + item.content + '</div>' +
                            '</div>' +
                            '</div>';
                    }
                });
                if (direction == 'bottom') {
                    $('#msgs').append(message);
                } else {
                    $('#msgs').prepend(message);
                }
                load_page++;
                hist.attr('page', load_page);
                if (r.data.length < 10) {
                    hist.attr('sw', 'off');
                } else {
                    hist.attr('sw', 'on');
                }

                $('#show').scrollTop($("#show")[0].scrollHeight);
            } else {
                hist.attr('sw', 'off');
            }
        }
    });
}

/**
 * 插入数据
 */
function insertAtCaret(obj, myValue) {
    var $t = obj[0];
    if (document.selection) {
        this.focus();
        sel = document.selection.createRange();
        sel.text = myValue;
        this.focus();
    } else if ($t.selectionStart || $t.selectionStart == '0') {
        var startPos = $t.selectionStart;
        var endPos = $t.selectionEnd;
        var scrollTop = $t.scrollTop;
        $t.value = $t.value.substring(0, startPos) + myValue + $t.value.substring(endPos, $t.value.length);
        this.focus();
        $t.selectionStart = startPos + myValue.length;
        $t.selectionEnd = startPos + myValue.length;
        $t.scrollTop = scrollTop;
    } else {
        this.value += myValue;
        this.focus();
    }
}

/**
 * 播放声音
 */
function playPrompt() {
    if ($('#new-chat').length > 0) {
        $('#new-chat')[0].play();
    }
}

/**
 * 清楚html标签
 * @param value
 * @returns {*|Window.jQuery}
 */
function htmlEncode(value) {
    return $('<div/>').text(value).html();
}

/**
 * 离线弹窗
 */
function offlinerecord() {
    hook('offlinerecordcheck', null, 1, function (check) {

        console.log(check);
        if (check.status == 'success') {
            /**
             * 打开留言弹窗
             */
            var openIndex = layer.open({
                type: 2,
                //title:'留言信息',
                shade: 0.3,
                closeBtn: 0,
                title: false,
                area: ['400px', '500px'],
                scrollbar: false,
                content: check.message,
                btn: ['确认留言', '关闭']
                , yes: function (index, layero) {
                    layer.getChildFrame('body', openIndex).find('.submit-button').click();
                }
                , btn2: function (index, layero) {
                    layer.close(index);
                }
            });
        }
    });

}

/**
 * 会员消费
 */
$("#user_pay").on('click', function () {

    var openIndex = layer.open({
        type: 2,
        title: '会员消费',
        skin: 'layui-layer-rim-record',
        area: ['300px', '400px'],
        content: IM_config.user_pay,
        btn: ['确认', '取消',],
        cancel: function (index, layero) {
            $(layero).find('a.layui-layer-close').prop('target', '_self');
        },
        yes: function (index, layero) {

            var to_id = youke_info.from_id;
            var to_nick = youke_info.from_nick;
            var to_avatar = youke_info.from_avatar;
            var from_id = kefu_info.to_id;
            var from_nick = kefu_info.to_nick;
            var from_avatar = kefu_info.to_avatar;

            var childframe = layer.getChildFrame('body', openIndex);
            var account = $(childframe).find('#account').val();
            var user = $(childframe).find('#user').val();
            var lists = $(childframe).find('#lists').val();
            var type = $(childframe).find('#type').val();
            var send = $(childframe).find('input[name="send"]:checked').val();
            var pay_type = $(childframe).find('input[name="pay_type"]:checked').val();
            if (!to_id) {
                layer.msg('请刷新重试')
                return false;
            }
            if (!lists) {
                layer.msg('请选择购买内容')
                return false;
            }

            var index = layer.load();
            var params = {
                to_id: to_id,
                to_nick: to_nick,
                to_avatar: to_avatar,
                from_id: from_id,
                from_nick: from_nick,
                from_avatar: from_avatar,
                id: lists,
                send: send,
                type: type,
                pay_type: pay_type,
                account: account,
                user: user,
            };
            console.log('params:', params);
            hook('user_pay', JSON.stringify(params), 1,function (result) {
                layer.close(index);
                if (result == false || result.status != 'success') layer.msg(result.message);
                if (result.pay_result == 'url') window.open(result.message);

                layer.close(openIndex);
            });

        },
    });
});

/**
 * 消费订单查询
 */
$("#user_list").on('click', function () {

    var openIndex = layer.open({
        type: 2,
        title: '订单查询',
        shade: 0.3,
        closeBtn: 1,
        area: ['400px', '500px'],
        scrollbar: false,
        content: IM_config.user_order,
        cancel: function (index, layero) {
            $(layero).find('a.layui-layer-close').prop('target', '_self');
        }
    });
});

